package free.mrchen.boot.gate.server.conf;

import free.mrchen.boot.gate.server.def.CustomRouteDefinitionLocator;
import free.mrchen.boot.gate.server.def.GateServerRouteProperties;
import free.mrchen.boot.gate.server.def.LocalStorageRouteDefFeature;
import free.mrchen.boot.gate.server.def.RouteDefFeature;
import free.mrchen.boot.gate.server.endpoint.RouteFeatureControllerEndpoint;
import free.mrchen.boot.gate.server.endpoint.RouteStableControllerEndpoint;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;

@RefreshScope
@Configuration
@EnableConfigurationProperties
public class GateServerRouteConfig {


    @Bean
    public GateServerRouteProperties gateServerRouteProperties() {
        return new GateServerRouteProperties();
    }

    @Bean
    public RouteDefFeature routeDefLocator(GateServerRouteProperties gateServerRouteProperties ) {
        if ( "local-storage".equals(gateServerRouteProperties.getMode()) ) {
            return new LocalStorageRouteDefFeature(gateServerRouteProperties.getBasePath());
        }
        throw new UnsupportedOperationException(gateServerRouteProperties.getMode());
    }


    @Bean
    public CustomRouteDefinitionLocator customRouteDefinitionLocator(
            GateServerRouteProperties gateServerRouteProperties ,
            RouteDefFeature routeDefFeature
    ) {
        return new CustomRouteDefinitionLocator( gateServerRouteProperties , routeDefFeature);
    }


    @Bean
    public RouteStableControllerEndpoint routeStableControllerEndpoint(RouteDefFeature routeDefFeature) {
        return new RouteStableControllerEndpoint(routeDefFeature);
    }

    @Bean
    public RouteFeatureControllerEndpoint routeFeatureControllerEndpoint(
            RouteDefFeature routeDefFeature ,
            org.springframework.cloud.context.scope.refresh.RefreshScope refreshScope
    ) {
        return new RouteFeatureControllerEndpoint( refreshScope , routeDefFeature );
    }


    @Bean
    public RouterFunction<ServerResponse> uiRouteLocator() {
        return RouterFunctions.resources( "/uit/**" , new ClassPathResource("webapps/"));
    }



}
